package sddz.foodmanage.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.zhy.autolayout.AutoLinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.adapter.WaitCheckAdapter;
import sddz.foodmanage.base.BaseActivity;
import sddz.foodmanage.model.WaitListBean;
import sddz.foodmanage.model.WaitshenheBean;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.DoubleUtil;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.MyUtils;
import sddz.foodmanage.utils.SpfUtils;

/**
 * @Date:2019/7/10
 * @Author:lbb 待核实详情页面
 */
public class WaitCheckActivity extends BaseActivity implements WaitCheckAdapter.ModifyCountInterface {

    @BindView(R.id.title_navigation_icon)
    ImageView titleNavigationIcon;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.title_menu_icon)
    ImageView titleMenuIcon;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.image_title_right)
    ImageView imageTitleRight;
    @BindView(R.id.wait_check)
    ListView waitCheck;
    @BindView(R.id.activity_wait_check)
    AutoLinearLayout activityWaitCheck;
    @BindView(R.id.tv_check)
    TextView tvCheck;
    @BindView(R.id.tv_totalprice)
    TextView tvTotalprice;
    @BindView(R.id.title_layout)
    AppBarLayout titleLayout;
    @BindView(R.id.tv_huitui)
    TextView tvHuitui;
    @BindView(R.id.tv_dinner_num)
    TextView tvDinnerNum;//用餐人数

    private List<WaitListBean.DataBean.GoodsBean> goodslist = new ArrayList<>();
    private WaitCheckAdapter adapter = new WaitCheckAdapter();
    WaitListBean.DataBean DataBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wait_check);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        if (adapter != null) {
            adapter.setModifyCountInterface(this);// 关键步骤2,设置数量增减接口
        }
    }

    private void initData() {
        Intent intent = getIntent();
        DataBean = (WaitListBean.DataBean) intent.getSerializableExtra("data");
        goodslist.addAll(DataBean.getGoods());
        adapter.setdata(mActivity, goodslist, SpfUtils.getUserData(mActivity).getType());
        waitCheck.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        tvTotalprice.setText("小计：" + DataBean.getTotal_price() + "元");
        tvDinnerNum.setText(DataBean.getDinner_num()+"");
    }

    private void initView() {
        titleText.setText("待审核详情");


    }

    @OnClick({R.id.title_navigation_icon, R.id.tv_check,R.id.tv_huitui})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_navigation_icon:
                finish();
                break;
            case R.id.tv_check://审核
                getcheck();
                break;
            case R.id.tv_huitui://回退
                backorder();
                break;
        }
    }
    //回退

    private void backorder() {
        dialog.show();
        Map<String,String> map=new HashMap<>();
        if(!TextUtils.isEmpty(DataBean.getId()+"")){
            map.put("id",DataBean.getId()+"");
            Log.e("回退id", JSON.toJSONString(map));
            HttpUtils.getInstance().POST(mActivity, API.getbackorder, JSON.toJSONString(map),SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
                @Override
                public void onSuccess(String body) {
                    dialog.dismiss();
                    if (!TextUtils.isEmpty(body)) {
                        Log.e("回退数据", body);
                        try {
                            JSONObject jsonObject = new JSONObject(body);
                            int code = jsonObject.optInt("status_code");
                            if (!jsonObject.optString("message").equals("")) {
                                show(jsonObject.optString("message"));
                            }
                            if (code == 200) {
                                finish();
                            } else if (code == 210) {
                                String token = jsonObject.optJSONObject("data").optString("token");
                                SpfUtils.savetoken(mActivity, token);
                                getcheck();
                            } else if (code == 401) {
                                SpfUtils.setLogin(mActivity, false);
                                startActivity(new Intent(mActivity, LoginActivity.class));
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(Request error, Exception e) {
                        dialog.dismiss();
                    show("访问数据失败，请稍后重试");
                }
            });
        }



    }

    /**
     * 审核
     */
    private void getcheck() {
        WaitshenheBean waitsh = new WaitshenheBean();
        List<WaitshenheBean.GoodsBean> wshgoodlist = new ArrayList<>();
        for (int a = 0; a < goodslist.size(); a++) {
            WaitshenheBean.GoodsBean goods = new WaitshenheBean.GoodsBean();
            goods.setId(goodslist.get(a).getId());
            goods.setAmount(goodslist.get(a).getAmount());
            wshgoodlist.add(goods);
        }
        waitsh.setId(DataBean.getId());
        waitsh.setGoods(wshgoodlist);
        Log.e("待审核传的数据", JSON.toJSONString(waitsh));
        dialog.show();
        HttpUtils.getInstance().POST(mActivity, API.getshenhe, JSON.toJSONString(waitsh), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                dialog.dismiss();

                Log.e("审核返回的数据", body);
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
                        if (!jsonObject.optString("message").equals("")) {
                            show(jsonObject.optString("message"));
                        }
                        if (code == 200) {
                            finish();
                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            Log.e("33333333", token);
                            SpfUtils.savetoken(mActivity, token);
                            getcheck();
                        } else if (code == 401) {
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Request error, Exception e) {
                dialog.dismiss();
            }
        });
    }

    //加
    @Override
    public void doIncrease(View showCountView, int position) {
        Log.e("jia", ((TextView) showCountView).getText().toString());
        Double add = DoubleUtil.add(Double.parseDouble(((TextView) showCountView).getText().toString()), Double.parseDouble("1"));
        ((TextView) showCountView).setText(add + "");
        goodslist.get(position).setAmount(add + "");
        Double he = 0.0;
        for (int i = 0; i < goodslist.size(); i++) {
            Double goodprice = DoubleUtil.mul(goodslist.get(i).getPrice(), Double.parseDouble(goodslist.get(i).getAmount()));
            he = DoubleUtil.add(he, goodprice);
        }
        tvTotalprice.setText("小计：" + he + "元");

    }

    //建
    @Override
    public void doDecrease(final View showCountView, final int position) {
        Double currentCount = Double.parseDouble(((TextView) showCountView).getText().toString());
        if (currentCount <= 1.0) {
            ((TextView) showCountView).setText(0 + "");

        } else {
            Double jian = DoubleUtil.sub(Double.parseDouble(((TextView) showCountView).getText().toString()), Double.parseDouble("1"));
            ((TextView) showCountView).setText(jian + "");
        }
        goodslist.get(position).setAmount(((TextView) showCountView).getText() + "");

        Double he = 0.0;
        for (int i = 0; i < goodslist.size(); i++) {
            Double goodprice = DoubleUtil.mul(goodslist.get(i).getPrice(), Double.parseDouble(goodslist.get(i).getAmount()));
            he = DoubleUtil.add(he, goodprice);
        }
        tvTotalprice.setText("小计：" + he + "元");
    }

    //输入
    @Override
    public void doTextView(final View showCountView, final int position) {
        final EditText inputServer = new EditText(mActivity);
        inputServer.setHint("请输入重量");
        inputServer.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
        inputServer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setView(inputServer)
                .setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (TextUtils.isEmpty(inputServer.getText().toString())) {//如果数量 为0，移除数据
                    ((TextView) showCountView).setText("0");
                    Log.e("空", "");
                    if (goodslist != null) {
                        goodslist.get(position).setAmount(((TextView) showCountView).getText() + "");
                    }

                }
                if (MyUtils.isDoubleOrFloat(inputServer.getText().toString())) {
                    ((TextView) showCountView).setText(inputServer.getText().toString());
                    if (goodslist != null) {
                        goodslist.get(position).setAmount(((TextView) showCountView).getText() + "");

                    } else {
                        ((TextView) showCountView).setText("0");//输入的数量不是double类型的，也默认为0，移除数据
                        if (goodslist != null) {
                            goodslist.get(position).setAmount(((TextView) showCountView).getText() + "");
                        }

                    }
                }
                Double he = 0.0;
                for (int i = 0; i < goodslist.size(); i++) {
                    Double goodprice = DoubleUtil.mul(goodslist.get(i).getPrice(), Double.parseDouble(goodslist.get(i).getAmount()));
                    he = DoubleUtil.add(he, goodprice);
                }
                tvTotalprice.setText("小计：" + he + "元");
            }
        });
        builder.show();
    }
}
